package com.rosense.client;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.concurrent.TimeUnit;

import com.rosense.client.rpc.IRPCServer;
import com.rosense.client.rpc.RPCBean;
import com.rosense.client.rpc.RPCClientLinux;
import com.rosense.client.rpc.RPCClientProcess;
import com.rosense.client.rpc.RpcIpBean;

/**
 * @author 李岩飞
 * @email eliyanfei@126.com	
 * 2018年1月23日 下午1:52:42
 * 
 */
public class LinuxMonitor {
	public static RpcIpBean ipBean = new RpcIpBean();

	/**
	 */
	public static void main(String[] args) {
		try {
			TimeUnit.SECONDS.sleep(5);
		} catch (Exception e) {
		}
		
		List<ResourceUsage> resourceList = new ArrayList<ResourceUsage>();
		resourceList.add(CpuUsage.getInstance());
		resourceList.add(MemUsage.getInstance());
		resourceList.add(NetUsage.getInstance());
		resourceList.add(IoUsage.getInstance());
		final String ip = getAddrss().getHostAddress();
		new Thread() {
			public void run() {
				try {
					IRPCServer<?> server = new RPCClientLinux();
					server.bind("rpc", 34567, ip);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.start();
		ipBean.ip = args[0];
		ipBean.port = args[1];
		if (args.length > 2) {
			ipBean.second = Integer.parseInt(args[2]);
		} else {
			ipBean.second = 120;
		}

		while (true) {
			try {
				RPCClientProcess client = new RPCClientProcess(ipBean.ip, ipBean.port);
				for (ResourceUsage resource : resourceList) {
					try {
						RPCBean rpc = resource.scan();
						rpc.setIp(ip);
						client.send(rpc);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			try {
				TimeUnit.SECONDS.sleep(ipBean.second);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	public static InetAddress getAddrss() {
		try {
			InetAddress candidateAddress = null;
			// 遍历所有的网络接口
			for (Enumeration ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements();) {
				NetworkInterface iface = (NetworkInterface) ifaces.nextElement();
				// 在所有的接口下再遍历IP
				for (Enumeration inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements();) {
					InetAddress inetAddr = (InetAddress) inetAddrs.nextElement();
					if (!inetAddr.isLoopbackAddress()) {// 排除loopback类型地址
						if (inetAddr.isSiteLocalAddress()) {
							// 如果是site-local地址，就是它了
							return inetAddr;
						} else if (candidateAddress == null) {
							// site-local类型的地址未被发现，先记录候选地址
							candidateAddress = inetAddr;
						}
					}
				}
			}
			if (candidateAddress != null) {
				return candidateAddress;
			}
			// 如果没有发现 non-loopback地址.只能用最次选的方案
			InetAddress jdkSuppliedAddress = InetAddress.getLocalHost();
			return jdkSuppliedAddress;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
